package org.nf.web.embed.server;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ClassUtil;
import jakarta.servlet.ServletContext;
import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.nf.web.config.Configure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @author wangliang
 * @date 2023/4/9
 */
public class TomcatServer extends AbstractWebServer {

    private final Logger log = LoggerFactory.getLogger(TomcatServer.class);

    private Tomcat tomcat;

    @Override
    protected ServletContext initServer(Configure configure) {
        tomcat = new Tomcat();
        tomcat.setPort(configure.getServer().getPort());
        tomcat.getConnector();
        String contextPath = configure.getServer().getContextPath();
        contextPath = "/".equals(contextPath) ? "" : contextPath;
        //设置webroot
        String webRoot = FileUtil.getWebRoot().getAbsolutePath() +
                File.separator + configure.getServer().getWebRoot();
        Context ctx = tomcat.addWebapp(contextPath, webRoot);
        //设置应用程序的目录
        WebResourceRoot resources = new StandardRoot(ctx);
        resources.addPreResources(new DirResourceSet(resources,
                "/WEB-INF/classes", ClassUtil.getClassPath(), "/"));
        ctx.setResources(resources);
        //返回ServletContext
        return ctx.getServletContext();
    }

    /**
     * 启动tomcat
     */
    @Override
    protected void start() {
        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            log.error("Start tomcat fail.", e);
        }
    }
}
